package com.henry.base.concurrency.aio;

import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AioTcpServer implements Runnable{
    private AsynchronousChannelGroup aysnchorhousChannelGroup;
    private AsynchronousServerSocketChannel listener;

    public AioTcpServer(int port) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(20);
        aysnchorhousChannelGroup = AsynchronousChannelGroup.withThreadPool(pool);
        listener = AsynchronousServerSocketChannel.open(aysnchorhousChannelGroup).bind(new InetSocketAddress(port));
    }

    @Override
    public void run() {
        try {
            AioAcceptHandler acceptHandler = new AioAcceptHandler();
            listener.accept(listener,acceptHandler);
            Thread.sleep(4000000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println("finished server");
        }
    }

    public static void main(String[] args) throws Exception {
        AioTcpServer server = new AioTcpServer(9008);
        new Thread(server).start();
    }
}
